package com.jnu.myllm.ui.intercepter;

import com.jnu.myllm.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("Authorization");
        if(jwt == null || jwt.isEmpty()) {
            return true;
        }
        System.out.println("jwt拦截器");
        Claims claims = null;
        response.setContentType("application/json;charset=utf-8");
        try{
            claims = Jwts.parser().setSigningKey("111222").parseClaimsJws(jwt).getBody();
        }catch (ExpiredJwtException ex){
            response.getWriter().print("{\"code\":4001,\"msg\":\"token过期，请重新登录\",\"data\":null}");
            return false;
        }catch (SignatureException ex){
            response.getWriter().print("{\"code\":4003,\"msg\":\"token被篡改，请警惕\",\"data\":null}");
            return false;
        }
        int userId = (Integer)claims.get("userId");
        String nickName = (String)claims.get("nickName");
        String loginName = (String)claims.get("loginName");
        int score=(Integer)claims.get("score");
        System.out.println("userId："+userId+"，nickName："+nickName+"，loginName："+loginName+"，score："+score);
        User u = new User();
        u.setId(userId);
        u.setLoginName(loginName);
        u.setNickName(nickName);
        u.setScore(score);
        request.setAttribute("user",u);
        return true;
    }
}
